﻿using CommerceOne.Common;
using CommerceOne.Domains.IRepositories;
using CommerceOne.Domains.SqlRepositories;
using CommerceOne.Models.Entities;

namespace CommerceOne.Widgets.LeftCategoryNav
{
    public class LeftCategoryNavController
    {
        /// <summary>
        /// Create instance of  IProductCategoryRepository
        /// </summary>
        private readonly IProductCategoryRepository _context = SqlProductCategoryRepository.Instance;

        /// <summary>
        /// Initializes a new instance of the <see cref="LeftCategoryNavController"/> class.
        /// </summary>
        public LeftCategoryNavController()
        {
        }

        /// <summary>
        /// Gets the view model.
        /// </summary>
        /// <returns></returns>
        public LeftCategoryViewModel GetViewModel(int? currentId)
        {
            var viewModel = new LeftCategoryViewModel { ProductCategories = this._context.LoadAllCategory(true) };
            if (viewModel.ProductCategories != null && currentId.HasValue)
            {
                var category = viewModel.ProductCategories.Find(p => p.ProductCategoryID == currentId.Value);
                if (category != null) category.IsActice = true;
            }
            if (viewModel.ProductCategories == null) return viewModel;
            foreach (var category in viewModel.ProductCategories)
            {
                category.Url = UrlBuilderService.Instance.GetUrlRoute(PageType.ProductList, category.ProductCategoryID, 1, category.Name, string.Empty);
                if (category.ChildCategory == null) continue;
                foreach (var subCateogry in category.ChildCategory)
                {
                    subCateogry.Url = UrlBuilderService.Instance.GetUrlRoute(PageType.ProductList, subCateogry.ProductCategoryID , 1, subCateogry.Name, string.Empty);
                }
            }
            return viewModel;
        }

        #region Singleton Instance
        private static LeftCategoryNavController _instance;

        public static LeftCategoryNavController Instance
        {
            get
            {
                if (_instance == null) _instance = new LeftCategoryNavController();
                return _instance;
            }
        }

        #endregion
    }
}